
/*
 * Copyright (C) 2019-2020 Yaong <yaongtime@gmail.com>
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include "vk_util.h"
#include "vc4_private.h"
#include "vc4_memory.h"

/*
 * Returns how much space a given descriptor type needs on a bo (GPU
 * memory).
 */
static uint32_t
descriptor_bo_size(VkDescriptorType type)
{
   switch(type) {
   case VK_DESCRIPTOR_TYPE_SAMPLER:
    //   return sizeof(struct vc4_sampler_descriptor);
   case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
    //   return sizeof(struct vc4_combined_image_sampler_descriptor);
   case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
   case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
   case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
    //   return sizeof(struct vc4_sampled_image_descriptor);
   default:
      return 0;
   }
}

VkResult
vc4_CreateDescriptorPool(VkDevice _device,
                        const VkDescriptorPoolCreateInfo *pCreateInfo,
                        const VkAllocationCallbacks *pAllocator,
                        VkDescriptorPool *pDescriptorPool)
{
   VC4_FROM_HANDLE(vc4_device, device, _device);
   struct vc4_descriptor_pool *pool;
   uint64_t size = sizeof(struct vc4_descriptor_pool);
   uint64_t bo_size = 0, bo_count = 0, dynamic_count = 0;

   for (unsigned i = 0; i < pCreateInfo->poolSizeCount; ++i) {
      if (pCreateInfo->pPoolSizes[i].type != VK_DESCRIPTOR_TYPE_SAMPLER)
         bo_count += pCreateInfo->pPoolSizes[i].descriptorCount;

            /* Verify supported descriptor type */
      switch(pCreateInfo->pPoolSizes[i].type) {
      case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
      case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
      case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
      case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
      case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
      case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
      case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
      case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
      case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
      case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
         dynamic_count += pCreateInfo->pPoolSizes[i].descriptorCount;
      default:
         break;
      }

      bo_size += descriptor_bo_size(pCreateInfo->pPoolSizes[i].type) *
                           pCreateInfo->pPoolSizes[i].descriptorCount;
   }

   if (!(pCreateInfo->flags & VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT)) {
      uint64_t host_size = pCreateInfo->maxSets * sizeof(struct vc4_descriptor_set);
      host_size += sizeof(struct vc4_descriptor) * dynamic_count;
      host_size += sizeof(struct vc4_bo*) * bo_count;
      size += host_size;
   } else {
      size += sizeof(struct vc4_descriptor_pool_entry) * pCreateInfo->maxSets;
   }

   pool = vk_object_zalloc(&device->vk, pAllocator, size,
                          VK_OBJECT_TYPE_DESCRIPTOR_POOL);
   if (!pool)
      return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);

   if (!(pCreateInfo->flags & VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT)) {
      pool->host_memory_base = (uint8_t*)pool + sizeof(struct vc4_descriptor_pool);
      pool->host_memory_ptr = pool->host_memory_base;
      pool->host_memory_end = (uint8_t*)pool + size;
   }

   if (bo_size > 0) {
      VkResult ret;

      ret = vc4_vk_bo_init_alloc(device, &pool->bo, bo_size);
      assert(ret == VK_SUCCESS);

      ret = vc4_bo_map(device, &pool->bo);
      assert(ret == VK_SUCCESS);
   }
   pool->size = bo_size;
   pool->max_entry_count = pCreateInfo->maxSets;

   *pDescriptorPool = vc4_descriptor_pool_to_handle(pool);
   return VK_SUCCESS;
}

static void
vc4_descriptor_set_destroy(struct vc4_device *device,
             struct vc4_descriptor_pool *pool,
             struct vc4_descriptor_set *set,
             bool free_bo)
{
   assert(!pool->host_memory_base);

   if (free_bo && set->size && !pool->host_memory_base) {
      uint32_t offset = (uint8_t*)set->mapped_ptr - (uint8_t*)pool->bo.map;
      for (int i = 0; i < pool->entry_count; ++i) {
         if (pool->entries[i].offset == offset) {
            memmove(&pool->entries[i], &pool->entries[i+1],
               sizeof(pool->entries[i]) * (pool->entry_count - i - 1));
            --pool->entry_count;
            break;
         }
      }
   }

   vk_object_free(&device->vk, NULL, set);
}

void
vc4_DestroyDescriptorPool(VkDevice _device,
                         VkDescriptorPool _pool,
                         const VkAllocationCallbacks *pAllocator)
{
   VC4_FROM_HANDLE(vc4_device, device, _device);
   VC4_FROM_HANDLE(vc4_descriptor_pool, pool, _pool);

   if (!pool)
      return;

   if (!pool->host_memory_base) {
      for(int i = 0; i < pool->entry_count; ++i) {
         vc4_descriptor_set_destroy(device, pool, pool->entries[i].set, false);
      }
   }

   if (pool->size)
      vc4_vk_bo_free_mem(device, &pool->bo);

   vk_object_free(&device->vk, pAllocator, pool);
}

static int
binding_compare(const void *av, const void *bv)
{
   const VkDescriptorSetLayoutBinding *a =
      (const VkDescriptorSetLayoutBinding *) av;
   const VkDescriptorSetLayoutBinding *b =
      (const VkDescriptorSetLayoutBinding *) bv;

   return (a->binding < b->binding) ? -1 : (a->binding > b->binding) ? 1 : 0;
}

static VkDescriptorSetLayoutBinding *
create_sorted_bindings(const VkDescriptorSetLayoutBinding *bindings,
                       unsigned count,
                       struct vc4_device *device,
                       const VkAllocationCallbacks *pAllocator)
{
   VkDescriptorSetLayoutBinding *sorted_bindings =
       vk_alloc2(&device->vk.alloc, pAllocator,
                 count * sizeof(VkDescriptorSetLayoutBinding),
                 8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);

   if (!sorted_bindings)
      return NULL;

   memcpy(sorted_bindings, bindings,
          count * sizeof(VkDescriptorSetLayoutBinding));

   qsort(sorted_bindings, count, sizeof(VkDescriptorSetLayoutBinding),
         binding_compare);

   return sorted_bindings;
}

VkResult
vc4_CreateDescriptorSetLayout(VkDevice _device,
                               const VkDescriptorSetLayoutCreateInfo *pCreateInfo,
                               const VkAllocationCallbacks *pAllocator,
                               VkDescriptorSetLayout *pSetLayout)
{
   VC4_FROM_HANDLE(vc4_device, device, _device);
   struct vc4_descriptor_set_layout *set_layout;

   assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO);

   int32_t max_binding = pCreateInfo->bindingCount > 0 ? 0 : -1;
   uint32_t immutable_sampler_count = 0;
   for (uint32_t j = 0; j < pCreateInfo->bindingCount; j++) {
      max_binding = MAX2(max_binding, pCreateInfo->pBindings[j].binding);

      /* From the Vulkan 1.1.97 spec for VkDescriptorSetLayoutBinding:
       *
       *    "If descriptorType specifies a VK_DESCRIPTOR_TYPE_SAMPLER or
       *    VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER type descriptor, then
       *    pImmutableSamplers can be used to initialize a set of immutable
       *    samplers. [...]  If descriptorType is not one of these descriptor
       *    types, then pImmutableSamplers is ignored.
       *
       * We need to be careful here and only parse pImmutableSamplers if we
       * have one of the right descriptor types.
       */
      VkDescriptorType desc_type = pCreateInfo->pBindings[j].descriptorType;
      if ((desc_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER ||
           desc_type == VK_DESCRIPTOR_TYPE_SAMPLER) &&
           pCreateInfo->pBindings[j].pImmutableSamplers) {
         immutable_sampler_count += pCreateInfo->pBindings[j].descriptorCount;
      }
   }

   uint32_t samplers_offset = sizeof(struct vc4_descriptor_set_layout) +
                              (max_binding + 1) * sizeof(struct vc4_descriptor_set_binding_layout);
   uint32_t size = samplers_offset +
                   immutable_sampler_count * sizeof(struct vc4_sampler);

   set_layout = vk_zalloc2(&device->vk.alloc, pAllocator,
                           size, 8,
                           VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
   if (!set_layout)
      return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);

   /* We just allocate all the immutable samplers at the end of the struct */
   struct vc4_sampler *samplers = (void*) &set_layout->binding[max_binding + 1];

   VkDescriptorSetLayoutBinding *bindings = NULL;
   if (pCreateInfo->bindingCount > 0) {
      assert(max_binding >= 0);
      bindings = create_sorted_bindings(pCreateInfo->pBindings,
                                        pCreateInfo->bindingCount,
                                        device, pAllocator);
      if (!bindings) {
         vk_free2(&device->vk.alloc, pAllocator, set_layout);
         return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
      }
   }

   memset(set_layout->binding, 0,
          size - sizeof(struct vc4_descriptor_set_layout));

   set_layout->binding_count = max_binding + 1;
   set_layout->flags = pCreateInfo->flags;
   set_layout->shader_stages = 0;
   set_layout->bo_size = 0;

   uint32_t descriptor_count = 0;
   uint32_t dynamic_offset_count = 0;

   for (uint32_t i = 0; i < pCreateInfo->bindingCount; i++) {
      const VkDescriptorSetLayoutBinding *binding = bindings + i;
      uint32_t binding_number = binding->binding;

      switch (binding->descriptorType) {
      case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
      case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
         break;
      case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
      case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
         set_layout->binding[binding_number].dynamic_offset_count = 1;
         break;
      case VK_DESCRIPTOR_TYPE_SAMPLER:
      case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
      case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
      case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
      case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
         /* Nothing here, just to keep the descriptor type filtering below */
         break;
      default:
         unreachable("Unknown descriptor type\n");
         break;
      }

      set_layout->binding[binding_number].type = binding->descriptorType;
      set_layout->binding[binding_number].array_size = binding->descriptorCount;
      set_layout->binding[binding_number].descriptor_index = descriptor_count;
      set_layout->binding[binding_number].dynamic_offset_index = dynamic_offset_count;

      if ((binding->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER ||
           binding->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) &&
           binding->pImmutableSamplers) {

         set_layout->binding[binding_number].immutable_samplers_offset = samplers_offset;

         for (uint32_t i = 0; i < binding->descriptorCount; i++)
            samplers[i] = *vc4_sampler_from_handle(binding->pImmutableSamplers[i]);

         samplers += binding->descriptorCount;
         samplers_offset += sizeof(struct vc4_sampler) * binding->descriptorCount;
      }

      descriptor_count += binding->descriptorCount;
      dynamic_offset_count += binding->descriptorCount *
                              set_layout->binding[binding_number].dynamic_offset_count;

      /* FIXME: right now we don't use shader_stages. We could explore if we
       * could use it to add another filter to upload or allocate the
       * descriptor data.
       */
      set_layout->shader_stages |= binding->stageFlags;

      set_layout->binding[binding_number].descriptor_offset = set_layout->bo_size;
      set_layout->bo_size += descriptor_bo_size(set_layout->binding[binding_number].type) *
                             binding->descriptorCount;
   }

   if (bindings)
      vk_free2(&device->vk.alloc, pAllocator, bindings);

   set_layout->descriptor_count = descriptor_count;
   set_layout->dynamic_offset_count = dynamic_offset_count;

   *pSetLayout = vc4_descriptor_set_layout_to_handle(set_layout);

   return VK_SUCCESS;
}

void
vc4_DestroyDescriptorSetLayout(VkDevice _device,
                                VkDescriptorSetLayout _set_layout,
                                const VkAllocationCallbacks *pAllocator)
{
   VC4_FROM_HANDLE(vc4_device, device, _device);
   VC4_FROM_HANDLE(vc4_descriptor_set_layout, set_layout, _set_layout);

   if (!set_layout)
      return;

   vk_free2(&device->vk.alloc, pAllocator, set_layout);
}

/*
 * As anv and tu already points:
 *
 * "Pipeline layouts.  These have nothing to do with the pipeline.  They are
 * just multiple descriptor set layouts pasted together."
 */

VkResult
vc4_CreatePipelineLayout(VkDevice _device,
                         const VkPipelineLayoutCreateInfo *pCreateInfo,
                         const VkAllocationCallbacks *pAllocator,
                         VkPipelineLayout *pPipelineLayout)
{
   VC4_FROM_HANDLE(vc4_device, device, _device);
   struct vc4_pipeline_layout *layout;

   assert(pCreateInfo->sType ==
          VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO);

   layout = vk_alloc2(&device->vk.alloc, pAllocator,
                      sizeof(struct vc4_pipeline_layout), 8,
                      VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
   if (layout == NULL)
      return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);

   layout->num_sets = pCreateInfo->setLayoutCount;

   uint32_t dynamic_offset_count = 0;
   for (uint32_t set = 0; set < pCreateInfo->setLayoutCount; set++) {
      VC4_FROM_HANDLE(vc4_descriptor_set_layout, set_layout,
                     pCreateInfo->pSetLayouts[set]);
      layout->set[set].layout = set_layout;

      layout->set[set].dynamic_offset_start = dynamic_offset_count;
      for (uint32_t b = 0; b < set_layout->binding_count; b++) {
         dynamic_offset_count += set_layout->binding[b].array_size *
            set_layout->binding[b].dynamic_offset_count;
      }
   }

   layout->push_constant_size = 0;
   for (unsigned i = 0; i < pCreateInfo->pushConstantRangeCount; ++i) {
      const VkPushConstantRange *range = pCreateInfo->pPushConstantRanges + i;
      layout->push_constant_size =
         MAX2(layout->push_constant_size, range->offset + range->size);
   }

   layout->push_constant_size = align(layout->push_constant_size, 4096);

   layout->dynamic_offset_count = dynamic_offset_count;

   *pPipelineLayout = vc4_pipeline_layout_to_handle(layout);

   return VK_SUCCESS;
}

void
vc4_DestroyPipelineLayout(VkDevice _device,
                          VkPipelineLayout _pipelineLayout,
                          const VkAllocationCallbacks *pAllocator)
{
   VC4_FROM_HANDLE(vc4_device, device, _device);
   VC4_FROM_HANDLE(vc4_pipeline_layout, pipeline_layout, _pipelineLayout);

   if (!pipeline_layout)
      return;
   vk_free2(&device->vk.alloc, pAllocator, pipeline_layout);
}

static VkResult
vc4_descriptor_set_create(struct vc4_device *device,
                          struct vc4_descriptor_pool *pool,
                          const struct vc4_descriptor_set_layout *layout,
                          struct vc4_descriptor_set **out_set)
{
   struct vc4_descriptor_set *set;
   uint32_t buffer_count = layout->descriptor_count;
   unsigned dynamic_offset = sizeof(struct vc4_descriptor_set) +
                             sizeof(struct vc4_bo *) * buffer_count;

   unsigned mem_size = dynamic_offset + layout->dynamic_offset_count + sizeof(struct vc4_descriptor) * buffer_count;

   if (pool->host_memory_base) {
      if (pool->host_memory_end - pool->host_memory_ptr < mem_size)
         return vk_error(device->instance, VK_ERROR_OUT_OF_POOL_MEMORY);

      set = (struct vc4_descriptor_set*)pool->host_memory_ptr;
      pool->host_memory_ptr += mem_size;
   } else {
      set = vk_alloc2(&device->vk.alloc, NULL, mem_size, 8,
                      VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);

      if (!set)
         return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
   }

   memset(set, 0, mem_size);
   vk_object_base_init(&device->vk, &set->base, VK_OBJECT_TYPE_DESCRIPTOR_SET);

   if (layout->dynamic_offset_count) {
      set->dynamic_descriptors = (uint32_t *)((uint8_t*)set + dynamic_offset);
   }

   set->layout = layout;
   set->pool = pool;
   uint32_t layout_size = layout->bo_size;
   // if (variable_count) {
   //    assert(layout->has_variable_descriptors);
   //    uint32_t stride = layout->binding[layout->binding_count - 1].size;
   //    layout_size = layout->binding[layout->binding_count - 1].offset +
   //                  *variable_count * stride;
   // }

   if (layout_size) {
      set->size = layout_size;

      if (!pool->host_memory_base && pool->entry_count == pool->max_entry_count) {
         vk_object_free(&device->vk, NULL, set);
         return vk_error(device->instance, VK_ERROR_OUT_OF_POOL_MEMORY);
      }

      /* try to allocate linearly first, so that we don't spend
       * time looking for gaps if the app only allocates &
       * resets via the pool. */
      if (pool->current_offset + layout_size <= pool->size) {
         set->mapped_ptr = (uint32_t*)(pool->bo.map + pool->current_offset);
         // set->va = pool->bo.iova + pool->current_offset;
         if (!pool->host_memory_base) {
            pool->entries[pool->entry_count].offset = pool->current_offset;
            pool->entries[pool->entry_count].size = layout_size;
            pool->entries[pool->entry_count].set = set;
            pool->entry_count++;
         }
         pool->current_offset += layout_size;
      } else if (!pool->host_memory_base) {
         uint64_t offset = 0;
         int index;

         for (index = 0; index < pool->entry_count; ++index) {
            if (pool->entries[index].offset - offset >= layout_size)
               break;
            offset = pool->entries[index].offset + pool->entries[index].size;
         }

         if (pool->size - offset < layout_size) {
            vk_object_free(&device->vk, NULL, set);
            return vk_error(device->instance, VK_ERROR_OUT_OF_POOL_MEMORY);
         }

         set->mapped_ptr = (uint32_t*)(pool->bo.map + offset);
         // set->va = pool->bo.iova + offset;
         memmove(&pool->entries[index + 1], &pool->entries[index],
            sizeof(pool->entries[0]) * (pool->entry_count - index));
         pool->entries[index].offset = offset;
         pool->entries[index].size = layout_size;
         pool->entries[index].set = set;
         pool->entry_count++;
      } else
         return vk_error(device->instance, VK_ERROR_OUT_OF_POOL_MEMORY);
   }

   // if (layout->has_immutable_samplers) {
   //    for (unsigned i = 0; i < layout->binding_count; ++i) {
   //       if (!layout->binding[i].immutable_samplers_offset)
   //          continue;

   //       unsigned offset = layout->binding[i].offset / 4;
   //       if (layout->binding[i].type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
   //          offset += A6XX_TEX_CONST_DWORDS;

   //       const struct vc4_sampler *samplers =
   //          (const struct vc4_sampler *)((const char *)layout +
   //                             layout->binding[i].immutable_samplers_offset);
   //       for (unsigned j = 0; j < layout->binding[i].array_size; ++j) {
   //          memcpy(set->mapped_ptr + offset, samplers[j].descriptor,
   //                 sizeof(samplers[j].descriptor));
   //          offset += layout->binding[i].size / 4;
   //       }
   //    }
   // }

   *out_set = set;
   return VK_SUCCESS;
}

VkResult
vc4_AllocateDescriptorSets(VkDevice _device,
                           const VkDescriptorSetAllocateInfo *pAllocateInfo,
                           VkDescriptorSet *pDescriptorSets)
{
   VC4_FROM_HANDLE(vc4_device, device, _device);
   VC4_FROM_HANDLE(vc4_descriptor_pool, pool, pAllocateInfo->descriptorPool);

   VkResult result = VK_SUCCESS;
   uint32_t i;
   struct vc4_descriptor_set *set = NULL;

   /* allocate a set of buffers for each shader to contain descriptors */
   for (i = 0; i < pAllocateInfo->descriptorSetCount; i++) {
      VC4_FROM_HANDLE(vc4_descriptor_set_layout, layout,
                      pAllocateInfo->pSetLayouts[i]);

      assert(!(layout->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR));

      result = vc4_descriptor_set_create(device, pool, layout, &set);
      if (result != VK_SUCCESS)
         break;

      pDescriptorSets[i] = vc4_descriptor_set_to_handle(set);
   }

   if (result != VK_SUCCESS) {
      vc4_FreeDescriptorSets(_device, pAllocateInfo->descriptorPool,
                             i, pDescriptorSets);
      for (i = 0; i < pAllocateInfo->descriptorSetCount; i++) {
         pDescriptorSets[i] = VK_NULL_HANDLE;
      }
   }
   return result;
}

VkResult
vc4_FreeDescriptorSets(VkDevice _device,
                      VkDescriptorPool descriptorPool,
                      uint32_t count,
                      const VkDescriptorSet *pDescriptorSets)
{
   VC4_FROM_HANDLE(vc4_device, device, _device);
   VC4_FROM_HANDLE(vc4_descriptor_pool, pool, descriptorPool);

   for (uint32_t i = 0; i < count; i++) {
      VC4_FROM_HANDLE(vc4_descriptor_set, set, pDescriptorSets[i]);

      if (set && !pool->host_memory_base)
         vc4_descriptor_set_destroy(device, pool, set, true);
   }
   return VK_SUCCESS;
}

static void
write_image_descriptor(VkDescriptorType desc_type,
                       struct vc4_descriptor_set *set,
                       const struct vc4_descriptor_set_binding_layout *binding_layout,
                       struct vc4_image_view *iview,
                       struct vc4_sampler *sampler,
                       uint32_t array_index)
{
   // void *desc_map = descriptor_bo_map(set, binding_layout, array_index);

   // if (iview) {
   //    const uint32_t tex_state_index =
   //       iview->type != VK_IMAGE_VIEW_TYPE_CUBE_ARRAY ||
   //       desc_type != VK_DESCRIPTOR_TYPE_STORAGE_IMAGE ? 0 : 1;
   //    memcpy(desc_map,
   //           iview->texture_shader_state[tex_state_index],
   //           sizeof(iview->texture_shader_state[0]));
   //    desc_map += offsetof(struct vc4_combined_image_sampler_descriptor,
   //                         sampler_state);
   // }

   // if (sampler && !binding_layout->immutable_samplers_offset) {
   //    /* For immutable samplers this was already done as part of the
   //     * descriptor set create, as that info can't change later
   //     */
   //    memcpy(desc_map,
   //           sampler->sampler_state,
   //           sizeof(sampler->sampler_state));
   // }
}

void
vc4_UpdateDescriptorSets(VkDevice  _device,
                          uint32_t descriptorWriteCount,
                          const VkWriteDescriptorSet *pDescriptorWrites,
                          uint32_t descriptorCopyCount,
                          const VkCopyDescriptorSet *pDescriptorCopies)
{
   for (uint32_t i = 0; i < descriptorWriteCount; i++) {
      const VkWriteDescriptorSet *writeset = &pDescriptorWrites[i];
      VC4_FROM_HANDLE(vc4_descriptor_set, set, writeset->dstSet);

      const struct vc4_descriptor_set_binding_layout *binding_layout =
         set->layout->binding + writeset->dstBinding;

      struct vc4_descriptor *descriptor = set->descriptors;

      descriptor += binding_layout->descriptor_index;
      descriptor += writeset->dstArrayElement;

      for (uint32_t j = 0; j < writeset->descriptorCount; ++j) {
         descriptor->type = writeset->descriptorType;

         switch(writeset->descriptorType) {

         case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
         case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
         case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
         case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: {
            const VkDescriptorBufferInfo *buffer_info = writeset->pBufferInfo + j;
            VC4_FROM_HANDLE(vc4_buffer, buffer, buffer_info->buffer);

            descriptor->buffer = buffer;
            descriptor->offset = buffer_info->offset;
            if (buffer_info->range == VK_WHOLE_SIZE) {
               descriptor->range = buffer->size - buffer_info->offset;
            } else {
               assert(descriptor->range <= UINT32_MAX);
               descriptor->range = buffer_info->range;
            }
            break;
         }
         case VK_DESCRIPTOR_TYPE_SAMPLER: {
            /* If we are here we shouldn't be modifying a immutable sampler,
             * so we don't ensure that would work or not crash. But let the
             * validation layers check that
             */
            const VkDescriptorImageInfo *image_info = writeset->pImageInfo + j;
            VC4_FROM_HANDLE(vc4_sampler, sampler, image_info->sampler);

            descriptor->sampler = sampler;

            write_image_descriptor(writeset->descriptorType,
                                   set, binding_layout, NULL, sampler,
                                   writeset->dstArrayElement + j);

            break;
         }
         case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
         case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
         case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
            const VkDescriptorImageInfo *image_info = writeset->pImageInfo + j;
            VC4_FROM_HANDLE(vc4_image_view, iview, image_info->imageView);

            descriptor->image_view = iview;

            write_image_descriptor(writeset->descriptorType,
                                   set, binding_layout, iview, NULL,
                                   writeset->dstArrayElement + j);

            break;
         }
         case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: {
            const VkDescriptorImageInfo *image_info = writeset->pImageInfo + j;
            VC4_FROM_HANDLE(vc4_image_view, iview, image_info->imageView);
            VC4_FROM_HANDLE(vc4_sampler, sampler, image_info->sampler);

            descriptor->image_view = iview;
            descriptor->sampler = sampler;

            write_image_descriptor(writeset->descriptorType,
                                   set, binding_layout, iview, sampler,
                                   writeset->dstArrayElement + j);

            break;
         }
         case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
         case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: {
            // VC4_FROM_HANDLE(vc4_buffer_view, buffer_view,
            //                  writeset->pTexelBufferView[j]);

            // assert(buffer_view);

            // descriptor->buffer_view = buffer_view;

            // write_buffer_view_descriptor(writeset->descriptorType,
            //                              set, binding_layout, buffer_view,
            //                              writeset->dstArrayElement + j);
            break;
         }
         default:
            unreachable("unimplemented descriptor type");
            break;
         }
         descriptor++;
      }
   }

   for (uint32_t i = 0; i < descriptorCopyCount; i++) {
      const VkCopyDescriptorSet *copyset = &pDescriptorCopies[i];
      VC4_FROM_HANDLE(vc4_descriptor_set, src_set,
                       copyset->srcSet);
      VC4_FROM_HANDLE(vc4_descriptor_set, dst_set,
                       copyset->dstSet);

      const struct vc4_descriptor_set_binding_layout *src_binding_layout =
         src_set->layout->binding + copyset->srcBinding;
      const struct vc4_descriptor_set_binding_layout *dst_binding_layout =
         dst_set->layout->binding + copyset->dstBinding;

      assert(src_binding_layout->type == dst_binding_layout->type);

      struct vc4_descriptor *src_descriptor = src_set->descriptors;
      struct vc4_descriptor *dst_descriptor = dst_set->descriptors;

      src_descriptor += src_binding_layout->descriptor_index;
      src_descriptor += copyset->srcArrayElement;

      dst_descriptor += dst_binding_layout->descriptor_index;
      dst_descriptor += copyset->dstArrayElement;

      // for (uint32_t j = 0; j < copyset->descriptorCount; j++) {
      //    *dst_descriptor = *src_descriptor;
      //    dst_descriptor++;
      //    src_descriptor++;

      //    if (descriptor_bo_size(src_binding_layout->type) > 0) {
      //       descriptor_bo_copy(dst_set, dst_binding_layout,
      //                          j + copyset->dstArrayElement,
      //                          src_set, src_binding_layout,
      //                          j + copyset->srcArrayElement);
      //    }

      // }
   }
}
